package com.qianbei.user.regist;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Request;
import com.qianbei.R;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.init.GlobalConfig;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.utilis.IDCard;
import com.qianbei.common.utilis.Util;
import com.qianbei.common.web.WebActivity;
import com.qianbei.user.model.UserMode;

import java.util.UUID;


public class RegisterActivity extends BaseActivity {
    private EditText et_mobile, et_identifyingCode, et_password;
    private TextView tv_identifyingCode, mAgreementTv;
    private String str_mobile, str_identifyingCode, str_password, name;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.kh_activity_register);

        setTitle("注册");
        initWidget();
    }

    private void initWidget() {
        et_mobile = (EditText) findViewById(R.id.et_mobile);
        et_identifyingCode = (EditText) findViewById(R.id.et_identifyingCode);
        et_password = (EditText) findViewById(R.id.et_password);

        mAgreementTv = (TextView) findViewById(R.id.tv_agreement);
        tv_identifyingCode = (TextView) findViewById(R.id.register_getcode);
        tv_identifyingCode.setOnClickListener(this);
        findViewById(R.id.btn_register).setOnClickListener(this);

        mAgreementTv.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        super.onClick(v);
        switch (v.getId()) {
            case R.id.register_getcode:
                String msg = checkUserInputValues(true);
                // String msg = "0";
                if (!"0".equals(msg)) {
                    new MsgAlert().show(msg);
                    return;
                } else {
                    // 获取注册验证码
                    registerCheck(str_mobile);
                    hideSoftInputFromWindow();
                }
                break;

            case R.id.btn_register:

                String msg1 = checkUserInputValues(false);
                if (!"0".equals(msg1)) {
                    new MsgAlert().show(msg1);
                    return;
                } else {
                    Register(str_mobile, str_identifyingCode, str_password, "");
                    Util.hideSoftInputFromWindow(v);
                }
                break;

            case R.id.tv_agreement:
                WebActivity.startWebActivity(RegisterActivity.this, REGIEST_AGREEMENT_URL);
                break;

            default:
                break;
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 22:
                    tv_identifyingCode.setText(msg.arg1 + "秒后重新获取");

                    if (msg.arg1 == 0) {
                        tv_identifyingCode.setClickable(true);
                        tv_identifyingCode.setText(R.string.menu_register_tv_identifyingCode);
                    } else {
                        Message msgs = new Message();
                        msgs.arg1 = msg.arg1 - 1;
                        msgs.what = 22;
                        handler.sendMessageDelayed(msgs, 1000);
                    }

                    break;

                default:
                    break;
            }

        }
    };

    /**
     * 获取验证码
     */
    private void registerCheck(String mobile) {
        ServerControl sc = new ServerControl(Request.Method.POST, PHONE_REGISTER,
                "mobile", mobile);
        sc.serverListener = new ServerControl.ServerListener() {

            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.isContinue) {
                    new MsgAlert().show(sr.bodyData.optString("msg"));
                    Message msgs = new Message();
                    msgs.arg1 = 60;
                    msgs.what = 22;
                    handler.sendMessageDelayed(msgs, 1000);
                    tv_identifyingCode.setClickable(false);

                }
            }
        };
        new ProgressDialog(mContext).startControl(sc, "获取验证码");
    }

    /**
     * 注册接口
     *
     * @param mobile
     * @param mobilecode
     * @param password
     * @parm uppercode
     */
    private void Register(final String mobile, String mobilecode,
                          final String password, String uppercode) {
        String uui = UUID.randomUUID().toString().replaceAll("-", "");
        ServerControl sc = new ServerControl(Request.Method.POST, USER_REGISTER,
                "mobile", mobile,
                "mobilecode", mobilecode,
                "password", password, "uppercode", uppercode

        );
        sc.serverListener = new ServerControl.ServerListener() {

            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.isContinue) {
                    UserMode mode = new UserMode();
                    mode.user_id = sr.bodyData.optJSONObject("data").optString("uid");
                    mode.phone_number = str_mobile;//用户手机号
                    mode.password = str_password;//用户密码
                    saveRegisterInfo(mode);



                }
            }
        };
        new ProgressDialog(mContext).startControl(sc, "正在注册");

    }

    private String checkUserInputValues(boolean isGetRegCode) // 手机号与密码的格式
    {

        str_mobile = et_mobile.getText().toString().trim();
        /** 电话号码验证 */
        if (TextUtils.isEmpty(str_mobile)) {
            return getString(R.string.menu_login_activity_check_mobile_null);
        }
        if (str_mobile.length() != 11 && !IDCard.isMobileNO(str_mobile)) {
            return getString(R.string.menu_login_activity_check_mobile_format);
        }
        if (isGetRegCode) {
            return "0";
        }

        str_identifyingCode = et_identifyingCode.getText().toString().trim();
        ;
        if (TextUtils.isEmpty(str_identifyingCode)) {
            return "验证码不能为空";
        }
        str_password = et_password.getText().toString().trim();
        ;
        if (TextUtils.isEmpty(str_password)) {
            return getString(R.string.menu_login_activity_check_password);
        }
        if (str_password.length() < 6 || str_password.length() > 16) {
            return getString(R.string.menu_register_activity_check_password_length_min);
        }
        String regex = "[A-Za-z0-9]+";
        if (!str_password.matches(regex)) {
            return getString(R.string.menu_register_activity_check_password_regex);
        }

        return "0";
    }

    private void saveRegisterInfo(UserMode mode) {

        SetData.setUserID(mode.user_id);
        SetData.setFace(mode.profile_image_url);
        SetData.sethxID(mode.easemob_name);
        SetData.sethxpass(mode.password);
        SetData.setUserPhone(str_mobile);


        SetData.setIdentity("0");
        GlobalConfig.getInstance().identity = "0";
    }


}
